<template>
  <div class="app-main-container">
    <!-- <div class="app-main-title">订单列表</div> -->
    <QueryForm
      v-model="filters"
      :query-form-config="queryFormConfig"
      @handleQuery="getList(1)"
      @clear="clear"
    >
      <template #btns>
        <el-button
          v-if="meta.indexOf('MealsPcOrderListExport') > -1"
          :loading="exportLoading"
          type="primary"
          @click="comboOrderExport"
        >{{ translate("export") }}</el-button>
      </template>
    </QueryForm>
    <el-table
      ref="table"
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      :header-row-class-name="'table-header'"
      class="doumee-element-tableb"
    >
      <el-table-column
        align="center"
        :label="translate('orderNum')"
        min-width="210"
        show-overflow-tooltip
      >
        <template v-slot="scope">
          <span class="ckxqBtn" @click="handleDetail(scope.row.orderId)">{{
            scope.row.orderId
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        :label="translate('cmoboContent')"
        prop="name"
        min-width="300"
        show-overflow-tooltip
      >
        <template slot-scope="scope">
          <span v-for="(item, index) in scope.row.orderInfo" :key="index">{{
            mealData(item)
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        :label="translate('total')"
        prop="allPrice"
        min-width="100"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        :label="translate('memberDisPrice')"
        prop="realPrice"
        min-width="100"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        :label="translate('orderSource')"
        min-width="100"
      >
        <template slot-scope="scope">
          <span>{{ scope.row.channelTypeName }}</span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        :label="translate('payMethod')"
        min-width="120"
      >
        <template slot-scope="scope">
          <span>{{ scope.row.payMethodName }}</span>
        </template>
      </el-table-column>
      <el-table-column
        :label="translate('memberInfo')"
        min-width="260"
        align="center"
        show-overflow-tooltip
      >
        <template slot-scope="scope">
          <span class="name">{{ scope.row.memberName }}</span>
          <span
            v-if="scope.row.memberPhone"
            class="phone"
          >-{{ scope.row.memberPhone }}</span>
          <span
            v-if="scope.row.memberCardId"
            class="phone"
          >-{{ scope.row.memberCardId }}</span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        :label="translate('bz')"
        prop="remarks"
        min-width="200"
        show-overflow-tooltip
      />
      <el-table-column
        :label="translate('operator')"
        prop="creator"
        min-width="120"
        align="center"
        show-overflow-tooltip
      />
      <el-table-column
        :label="translate('createTime')"
        prop="createTime"
        min-width="160"
        align="center"
      />
      <el-table-column
        :label="translate('orderStatus')"
        prop="createTime"
        fixed="right"
        min-width="100"
        align="center"
        show-overflow-tooltip
      >
        <!-- status -->
        <template slot-scope="scope">
          <span
            v-if="scope.row.status == '0'"
            class="primaryColor pointer"
            @click="getOrderType(scope.row.orderId)"
          >{{ scope.row.statusName }}</span>
          <span v-else>{{ scope.row.statusName }}</span>
        </template>
      </el-table-column>
      <el-table-column
        :label="translate('handle')"
        min-width="160"
        align="center"
        fixed="right"
      >
        <template slot-scope="scope">
          <div class="flex-cc">
            <div
              v-if="
                scope.row.status == '0' &&
                  meta.indexOf('ComboOrderPayCancel') > -1
              "
            >
              <el-button
                v-preventReClick
                type="text"
                @click="cancleBuy(scope.row.orderId)"
              >{{ translate("cancelBuy") }}</el-button>
            </div>
            <div v-else-if="scope.row.status == '3'">
              <el-button
                v-if="meta.indexOf('ComboOrderCancel') > -1"
                v-preventReClick
                type="text"
                @click="mealRefund(scope.row.orderId)"
              >{{ translate("comboRefund") }}</el-button>
              <el-button
                v-if="meta.indexOf('ComboPrinterOrder') > -1"
                v-preventReClick
                type="text"
                @click="printTic(scope.row.orderId)"
              >{{ translate("printReceipt") }}</el-button>
            </div>
            <div v-else>-</div>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <Paginations
      :total="total"
      :page="pagination.page"
      @current-change="getList"
      @SizeChange="handleSizeChange"
    />
    <ComboDetail ref="ComboDetailRef" />
    <ComboTem v-if="isPrint" ref="ComboTemRef" />
  </div>
</template>

<script>
import { getChannelType, mealOrderbList, mealCancel, mealRefund, getOrderTypeQuery, printOrder, orderbType, allConfigList, mealOrderExport } from '@/api'
import { parseTime, parseTimeb } from '@/utils'
import QueryForm from '@/components/QueryForm'
import ComboDetail from './detail.vue'
import { TJshortcuts } from '@/utils/config'
import ComboTem from '@/components/printTem/combo.vue'
export default {
  name: 'ComboOrderList',
  components: {
    ComboTem,
    QueryForm,
    ComboDetail
  },
  data() {
    return {
      exportLoading: false,
      isPrint: false,
      queryFormConfig: {
        formItems: [{
          filed: 'orderId',
          type: 'input',
          label: this.translate('orderNum'),
          placeholder: this.translate('placeOrderNum'),
          clearable: true
        }, {
          filed: 'mealsName',
          type: 'input',
          label: this.translate('tcname'),
          placeholder: this.translate('tcnameplace'),
          clearable: true
        }, {
          filed: 'channelType',
          type: 'select',
          label: this.translate('orderSource'),
          placeholder: this.translate('orderSourceplace'),
          clearable: true,
          options: []
        }, {
          filed: 'payMethod',
          type: 'select',
          label: this.translate('zflx'),
          placeholder: this.translate('zflxpplace'),
          clearable: true,
          options: []
        }, {
          filed: 'payStatus',
          type: 'select',
          label: this.translate('orderStatus'),
          placeholder: this.translate('orderStatusplace'),
          clearable: true,
          labelCode: 'name',
          options: []
        }, {
          filed: 'time',
          type: 'daterange',
          clearable: true,
          pickerOptions: {
            shortcuts: TJshortcuts
          }
        }, {
          filed: 'memberInfo',
          type: 'input',
          label: this.translate('memberInfo'),
          placeholder: this.translate('memberInfoPlace'),
          clearable: true
        }],
        online: true
      },
      meta: [],
      list: [],
      pagination: {
        page: 1,
        rows: 10
      },
      total: 0,
      payTypes: [],
      listLoading: true,
      filters: {
        time: [parseTimeb(7).slice(0, 10), parseTime(new Date()).slice(0, 10)]
      }
    }
  },
  created() {
    this.meta = this.$route.meta.buttons || []
    this.initData()
    this.getChannel()
    this.getOrderStatusList()
    this.getList(1)
  },
  mounted() {
    this.$nextTick(() => {
      this.$refs.table.doLayout()
    })
  },
  activated() {
    this.$nextTick(() => {
      this.$refs.table.doLayout()
    })
  },
  methods: {
    getChannel() {
      getChannelType({ param: { code: 'CHANNEL_MEALS' }}).then(res => {
        this.queryFormConfig.formItems[2].options = res.recordList.map(item => {
          return {
            label: item.name,
            value: item.value
          }
        })
      })
    },
    getOrderStatusList() {
      getOrderTypeQuery({ param: {}}).then(res => {
        this.queryFormConfig.formItems[4].options = res.recordList || []
      })
    },
    handleSizeChange(value) {
      this.pagination.rows = value
      this.getList(1)
    },
    handleDetail(orderId) {
      this.$refs.ComboDetailRef.getOrderDetail(orderId)
    },
    comboOrderExport() {
      const { filters } = this
      if (filters.time && filters.time.length > 0) {
        filters.startDate = filters.time[0] + ' 00:00:00'
        filters.endDate = filters.time[1] + ' 23:59:59'
      } else {
        filters.startDate = null
        filters.endDate = null
      }
      this.exportLoading = true
      mealOrderExport({
        param: {
          ...filters,
          venueId: sessionStorage.getItem('venueId')
        }
      }).then((res) => {
        this.exportLoading = false
        if (res.errorCode === '000000') {
          const a = document.createElement('a') // 创建一个a标签元素
          a.style.display = 'none' // 设置元素不可见
          a.href = res.record.showUrl // 设置下载地址
          document.body.appendChild(a) // 加入
          a.click() // 触发点击,下载
          document.body.removeChild(a) //
          this.$message.success(this.translate('dccg'))
        }
      })
        .catch(() => {
          this.exportLoading = false
        })
    },
    getOrderType(orderId) {
      orderbType({
        param: {
          orderId
        }
      })
        .then((res) => {
          const str = res.record.msg
          if (res.errorCode === '000000') {
            if (res.record.code === '0') {
              this.$message.success(str)
              this.getList()
            } else if (res.record.code === '2') {
              this.$message.info(str)
            } else {
              this.$message.error(str)
              this.getList()
            }
          }
        })
        .catch((err) => {
          console.log(err)
        })
    },
    mealData(meal) {
      if (meal.validityType === '1') {
        return meal.name + (meal.type !== '1' ? ` ${this.translate('cs')}：` + meal.num + this.translate('degree') : '') + (meal.type === '2' || meal.type === '0' ? ` ${this.translate('zscs')}：` + meal.giveNums + this.translate('degree') : '') + ` ${this.translate('num')}：` + meal.mealsNum + ` ${this.translate('indate')}：` + meal.indate + this.translate('days') + ` ${this.translate('oldprice')}：` + meal.price
      } if (meal.validityType === '2') {
        return meal.name + (meal.type !== '1' ? ` ${this.translate('cs')}：` + meal.num + this.translate('degree') : '') + (meal.type === '2' || meal.type === '0' ? ` ${this.translate('zscs')}：` + meal.giveNums + this.translate('degree') : '') + ` ${this.translate('num')}：` + meal.mealsNum + ` ${this.translate('indate')}：` + meal.validityStartTime + ' - ' + meal.validityEndTime + ` ${this.translate('oldprice')}：` + meal.price
      } else {
        return meal.name + (meal.type !== '1' ? ` ${this.translate('cs')}：` + meal.num + this.translate('degree') : '') + (meal.type === '2' || meal.type === '0' ? ` ${this.translate('zscs')}：` + meal.giveNums + this.translate('degree') : '') + ` ${this.translate('num')}：` + meal.mealsNum + ` ${this.translate('fixDate')}：` + meal.validityStartTime + ' - ' + meal.validityEndTime + ` ${this.translate('oldprice')}：` + meal.price
      }
    },
    rStatus(status) {
      switch (status) {
        case '0':
          return this.translate('useStatus3')
        case '1':
          return this.translate('useStatus5')
        case '2':
          return this.translate('useStatus6')
        case '3':
          return this.translate('zfcg')
        case '4':
          return this.translate('useStatus7')
        case '5':
          return this.translate('useStatus8')
        default:
          return ''
      }
    },
    nameWithPayMethod(payM) {
      const payType = this.payTypes.find((item) => item.value === payM)
      return payType ? payType.name : '-'
    },
    initData() {
      allConfigList({ param: { type: '2', code: '1' }}).then(res => {
        if (res.errorCode === '000000') {
          const arrb = res.recordList
          arrb.forEach(e => {
            e.label = e.name
          })
          this.queryFormConfig.formItems[3].options = arrb
          this.payTypes = res.recordList
        }
      }).catch(err => {
        console.log(err)
      })
    },
    getList(page) {
      const { filters, pagination } = this
      if (page) {
        pagination.page = page
        this.pagination.page = Number(page)
      }
      pagination.firstQueryTime = parseTime(new Date())
      if (filters.time && filters.time.length > 0) {
        filters.startDate = filters.time[0] + ' 00:00:00'
        filters.endDate = filters.time[1] + ' 23:59:59'
      } else {
        filters.startDate = null
        filters.endDate = null
      }
      this.listLoading = true
      mealOrderbList({
        pagination, param: {
          ...filters,
          venueId: sessionStorage.getItem('venueId')
        }
      }).then(res => {
        this.listLoading = false
        if (res.errorCode === '000000') {
          this.list = res.recordList
          this.total = res.totalCount
          if (res.totalCount && res.recordList.length === 0 && pagination.page > 1) {
            this.getList(Math.ceil(res.totalCount / pagination.rows))
          }
        }
      }).catch(() => {
        this.listLoading = false
      })
    },
    clear() {
      this.filters = { time: [] }
      this.getList(1)
    },
    cancleBuy(id) {
      this.$alert(this.translate('cancelBugComboPlace'), this.translate('warning'), {
        confirmButtonText: this.translate('qd'),
        callback: action => {
          if (action === 'confirm') {
            mealCancel({ param: { id }}).then(res => {
              if (res.errorCode === '000000') {
                this.getList()
              }
            })
          }
        }
      })
    },
    mealRefund(id) {
      // 退款
      this.$alert(this.translate('refundComboPlace'), this.translate('warning'), {
        confirmButtonText: this.translate('qd'),
        callback: action => {
          if (action === 'confirm') {
            mealRefund({ param: { id }})
              .then(res => {
                if (res.errorCode === '000000') {
                  this.getList()
                }
              })
          }
        }
      })
    },
    printTic(id) {
      // 打印小票
      const venueId = sessionStorage.getItem('venueId')
      this.isPrint = true
      printOrder({ param: { venueId, templateCode: 'MEALSTPML', workId: id }}).then(res => {
        if (res.errorCode === '000000') {
          if (res.record && res.record.isPrint === '1' && res.record.dataList && res.record.dataList.length > 0) {
            res.record.dataList.forEach(item => {
              this.$refs.ComboTemRef.obj = { ...item }
              setTimeout(() => {
                this.$refs.ComboTemRef.print()
              }, 300)
              setTimeout(() => {
                this.isPrint = false
              }, 500)
            })
          } else {
            this.isPrint = false
          }
        } else {
          this.isPrint = false
        }
      }).catch((err) => {
        this.isPrint = false
        console.log(err)
      })
    }
  }
}
</script>

<style lang='scss' scoped>
.division-line {
  text-align: center;
  display: inline-block;
  color: #999;
  width: 30px;
}

.bottom-style {
  height: 50px;
  border-left: 1px #dfe2e8 solid;
  border-right: 1px #dfe2e8 solid;
  border-bottom: 1px #dfe2e8 solid;
  .sum-style {
    margin-left: 10px;
    margin-top: 17px;
    height: 15px;
    float: left;
    .sum-title {
      color: #222;
      font-size: 13px;
    }
    .sum-value {
      color: #dd0707;
      font-size: 17px;
      font-weight: 700;
    }
  }
  .btn-style {
    float: right;
    width: 80px;
    height: 30px;
    margin-right: 10px;
    margin-top: 10px;
    background-color: #1943a9;
    color: #fff;
    text-align: center;
    border-radius: 4px;
    line-height: 30px;
    font-size: 13px;
    font-weight: 700;
  }
}
.ticket-style {
  display: inline-block;
  width: 20px;
  height: 20px;
  border: #999 solid 1px;
  border-radius: 10px;
  text-align: center;
  p {
    vertical-align: middle;
    font-weight: 700;
    font-size: 18px;
    line-height: 20px;
    color: #999;
    margin: 0;
  }
}

.count-style {
  margin-left: 5px;
  margin-right: 5px;
}
.pay-style {
  min-width: 80px;
  padding-left: 5px;
  padding-right: 5px;
  height: 30px;
  font-size: 15px;
  line-height: 1px;
  vertical-align: middle;
}
.slelect-pay-style {
  background-color: #1943a9;
  color: #fff;
}
.normal-pay-style {
  border: 1px solid #d8d8d8;
  background-color: #fff;
  color: #222;
}
.messgae-style {
  color: #dd0707;
}
.price-style {
  font-size: 17px;
  font-weight: 500;
}
.unit-style {
  margin-right: 20px;
}
.bottom-speace-style {
  margin-bottom: 10px;
}
.card-message {
  // width: 80%;
  margin-bottom: 10px;
  background-color: #f2f2f2;
  height: 60px;
  line-height: 20px;
  .first-line {
    height: 30px;
    overflow: hidden;
    padding: 5px;
    .message-title-style {
      color: #999;
    }
    .card-name-style {
      display: inline-block;
      border: 1px #999 solid;
      border-radius: 4px;
      background-color: #fff;
      font-size: 12px;
      padding-left: 5px;
      padding-right: 5px;
      height: 20px;
      text-align: center;
    }
    .close-style {
      font-size: 20px;
      float: right;
      margin-right: 5px;
      margin-top: -2px;
      padding: 0;
      border: 0px #999 solid;
    }
    .message-value-style {
      margin-right: 15px;
      color: #222;
    }
  }
}
.footer-style {
  display: flex;
  justify-content: space-between;
  background-color: #f2f2f2;
  margin: -10px -20px -30px;
  height: 50px;
  .bottom-left {
    margin-left: 20px;
    height: 20px;
    margin-top: 15px;
    .sum-title-style {
      font-size: 15px;
      color: #222;
    }
    .sum-pay-value-style {
      font-size: 17px;
      font-weight: 500;
      color: #dd0707;
    }
    .dis-title-style {
      font-size: 14px;
      color: #222;
    }
    .discoun-style {
      font-size: 16px;
      color: #dd0707;
    }
  }
  .bottom-right {
    margin-right: 20px;
    margin-top: 10px;
    height: 30px;
    .pay-action-style {
      width: 100px;
      height: 30px;
      font-size: 15px;
      line-height: 1px;
      vertical-align: middle;
    }
  }
}
</style>
